﻿using FlexFlow.Base.Interface;
using FlexFlow.Model;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlexFlow.DataProvider.MongoDB
{
    /// <summary>
    /// 表示基于MongoDB的用户关系实体提供者
    /// </summary>
    public sealed class MongoDbUserRelationProvider : MongoDBPhysicalModelProvider<UserRelation>, IUserRelationProvider
    {
        /// <summary>
        /// 创建一个新的用户关系实体
        /// </summary>
        /// <returns>
        /// 创建的实体
        /// </returns>
        public override UserRelation Create()
        {
            return new UserRelation();
        }
        /// <summary>
        /// 取得具有指定ID的组织机构下的成员关系列表
        /// </summary>
        /// <param name="orgId">
        /// 要取得成员列表的组织机构ID
        /// </param>
        /// <returns>
        /// 取得的成员关系列表
        /// </returns>
        public List<UserRelation> GetRelations(Guid orgId)
        {
            IMongoCollection<UserRelation> col = GetCollection();
            FilterDefinition<UserRelation> filter = (FilterDefinition<UserRelation>)(m => m.Organization == orgId);
            return col.GetAll(filter);
        }
        /// <summary>
        /// 检查指定组织机构与指定成员的关联是否已经存在
        /// </summary>
        /// <param name="orgId">
        /// 要检查的组织机构ID
        /// </param>
        /// <param name="memberId">
        /// 要检查的成员ID
        /// </param>
        /// <returns>
        /// 一个表示是否存在的值
        /// </returns>
        public bool Exist(Guid orgId, Guid memberId)
        {
            return Get(orgId, memberId) != null;
        }

        /// <summary>
        /// 取得指定组织机构与指定成员的关联实例
        /// </summary>
        /// <param name="orgId">
        /// 要取得的关联的组织机构ID
        /// </param>
        /// <param name="memberId">
        /// 要取得的关联的成员ID
        /// </param>
        /// <returns>
        /// 取得的关联实体
        /// </returns>
        public UserRelation Get(Guid orgId, Guid memberId)
        {
            IMongoCollection<UserRelation> col = GetCollection();
            FilterDefinition<UserRelation> filter = (FilterDefinition<UserRelation>)(m => m.Organization == orgId && m.Member == memberId);
            return col.FirstOrDefault(filter);
        }
        /// <summary>
        /// 设定指定ID的关系关联的组织机构
        /// </summary>
        /// <param name="relId">
        /// 要设置的关系ID
        /// </param>
        /// <param name="OrgId">
        /// 要设置的组织机构ID
        /// </param>
        /// <returns>
        /// 一个表示是否设置成功的值
        /// </returns>
        public bool SetOrg(Guid relId, Guid OrgId)
        {
            UpdateDefinition<UserRelation> upDef = 
                Builders<UserRelation>.Update
                .Set(m => m.Organization, OrgId)
                .Set(m => m.Tag, "指派");
            return Update(relId, upDef);
        }
    }
}
